package secondBrush.hash;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class E08Leetcode18 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        int length = nums.length;
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < length; i++) {

            if (nums[i] > target && nums[i] >= 0) {
                break;
            }

            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            for (int j = i + 1; j < length; j++) {
                int left = j + 1;
                int right = length - 1;

                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }

                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    }else {
                        result.add(new ArrayList<>(Arrays.asList(nums[i], nums[j], nums[left], nums[right])));

                        while (right > left && nums[left] == nums[left + 1]) left++;
                        while (right > left && nums[right] == nums[right - 1]) right--;

                        left++;
                        right--;
                    }

                }

            }
        }
        return result;
    }
}
